﻿using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMainTask.IMainTaskParsers;
using HamcoWcs.Entitys.MainTasks;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.EdgeInfos;
using HamcoWcs.Service.Common;
using System;

namespace HamcoWcs.Service.MainTasks.SubTaskParsers
{
    /// <summary>
    /// 堆垛机入库任务解析器
    /// </summary>
    [AutoInject(typeof(ISubTaskParser), InjectType.Scope)]
    public class SubTaskParser_SrmInTask : SubTaskParserBase
    {
        public override EnumSubTaskType SubTaskType => EnumSubTaskType.SrmInTask;
        public SubTaskParser_SrmInTask(ILocationService locationService) : base(locationService)
        {
        }

        public override void Deal(MainTask mainTask, EdgeInfoDto edge)
        {
            //var extend = JsonConvert.DeserializeObject<ExtendDto>(mainTask.Extend);
            //if (extend == null) throw new Exception($"未获取到任务[{mainTask.TaskId}]的扩展信息");

            if (string.IsNullOrEmpty(mainTask.DesPosition))
            {
                var tloc = _locationService.GetEmptyLocation(mainTask.DesZone);
                // 建任务的时候预约好货架，可以在货位预约满后拒绝MES指令，防止爆仓
                if (tloc == null) throw new Exception($"未在[{mainTask.DesZone}]中找到空货架");

                mainTask.DesPosition = tloc.WcsLocName;
                //mainTask.Extend = JsonConvert.SerializeObject(extend);
            }

            //var subTask = CreateNewSubTask(mainTask, edge.FromNode, extend.ToAddress.PositionName, edge.ExcutePlc);
            var subTask = CreateNewSubTask(mainTask, edge.FromNode, mainTask.DesPosition, edge.ExcutePlc);
            mainTask.SubTasks.Add(subTask);

            //mainTask.SubTasks.Add(new SubTask()
            //{
            //    TaskFrom = mainTask.Sender,
            //    SubTaskId = "",
            //    SubTaskType = SubTaskType.ToString(),
            //    TaskStatus = EnumSubTaskStatus.NewTask.ToString(),
            //    UnitId = mainTask.UnitId,
            //    TaskSeq = mainTask.SubTasks.Count + 1,
            //    FromLoc = edge.FromNode,
            //    ToLoc = edge.ToNode,
            //    PlcName = edge.ExcutePlc
            //});
        }
    }
}

